# -*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
import json
from models import User
from billing.models import Consumption , Charge
from forms import UserForm
from . import settings
from keystone_util import Keystone
from django.db.models import Q
import decimal
from decimal import Decimal
from django.utils import timezone
import datetime

def register(req):
    login_url = settings.LOGIN_URL
    user_status = settings.USER_CHECK_STATUS
    keyclient = Keystone()
    v_client = keyclient.login(settings.OPENSTACK_ADMIN_USER,settings.OPENSTACK_ADMIN_PASS,settings.OPENSTACK_ADMIN_TENANT)
    enable =True
    responseText={'login_url':login_url}
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            email = uf.cleaned_data['email']
            phone = uf.cleaned_data['phone']
            try:
                if user_status == 1:
                    tenant = keyclient.create_tenant(v_client,username,username,enable)
                    user = keyclient.create_user(v_client,username,password,tenant,email,enable)
                    registAdd = User.objects.get_or_create(username = username,password = password,email = email,phone = phone,is_active = user_status,keystone_user_id=user.id)[1]    
                else :
                    registAdd = User.objects.get_or_create(username = username,password = password,email = email,phone = phone,is_active = user_status)[1]
                responseText['registAdd'] = registAdd
                if  registAdd == True:
                    responseText['status'] = str(username)+'注册成功'
                else:
                    responseText['status'] = '注册失败,请重新注册>>'
            except:
                responseText['registAdd'] = False
                responseText['status'] = '注册异常,请重新注册>>'
        else:
            responseText['registAdd'] = False 
            responseText['status'] = '用户信息无效,请重新注册'
        return render_to_response('register/regist_result.html',responseText)
    else:
        uf = UserForm()
        return render_to_response('register/regist.html',{'uf':uf,'login_url':login_url},context_instance=RequestContext(req))

def list_all_users(req,user_type):
    page = req.GET.get('page')
    user_list = User.objects.filter(is_active = user_type)
    paginator = Paginator(user_list, settings.PAGE_ITEMS_SHOW) # Show 25 contacts per page
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
    # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render_to_response('register/list_all_users.html', {'contacts':contacts,'user_type':user_type}, context_instance=RequestContext(req))

def check_user_pass(req,user_id,page_num):
    
    obj = User.objects.get(id=user_id)
    user_type=obj.is_active
    username = settings.OPENSTACK_ADMIN_USER
    password = settings.OPENSTACK_ADMIN_PASS
    tenant_name = settings.OPENSTACK_ADMIN_TENANT
    enable = True
    keyclient = Keystone()
    
    v_client = keyclient.login(username,password,tenant_name)
    #由未审核(刚注册状态)转为审核通过状态
    try:
        if obj.is_active == 0 :
            tenant = keyclient.create_tenant(v_client,obj.username,obj.username,enable)
            user = keyclient.create_user(v_client,obj.username,obj.password,tenant,obj.email,enable)
            obj.keystone_user_id = user.id
            
        #由审核通过状态转为审核未通过状态   
        else :
            if obj.keystone_user_id != None :
                keyclient.update_user_state(v_client,obj.keystone_user_id,True);
            else:
                tenant = keyclient.create_tenant(v_client,obj.username,obj.username,enable)
                user = keyclient.create_user(v_client,obj.username,obj.password,tenant,obj.email,enable)
                obj.keystone_user_id = user.id  
    except:
        print "工程不存在"
    obj.is_active = 1
    obj.save()
    return redirect('/list_all_users/'+str(user_type)+'/?page='+page_num)

def check_user_nopass(req,user_id,page_num):
    
    obj = User.objects.get(id=user_id)
    user_type=obj.is_active
    
    #由审核通过转为审核未通过状态
    if obj.is_active == 1 :
        username = settings.OPENSTACK_ADMIN_USER
        password = settings.OPENSTACK_ADMIN_PASS
        tenant_name = settings.OPENSTACK_ADMIN_TENANT
        enable = False
        keyclient = Keystone()
        v_client = keyclient.login(username,password,tenant_name)
        keyclient.update_user_state(v_client,obj.keystone_user_id,enable);
        
    obj.is_active = 2    
    obj.save()
    return redirect('/list_all_users/'+str(user_type)+'/?page='+page_num)

def search(req):  
    
    user_type = req.POST.get("user_type")  
    keyword = req.POST.get("keyword")  
    print user_type
    print keyword
    #多个字段模糊查询， 括号中的下划线是双下划线，双下划线前是字段名，双下划线后可以是icontains或contains,区别是是否大小写敏感，竖线是或的意思  
    page = req.GET.get('page')
    user_list = User.objects.filter(Q(username__icontains=keyword)|Q(email__icontains=keyword)|Q(phone__icontains=keyword)|Q(extra__icontains=keyword)).filter(is_active = user_type)
    paginator = Paginator(user_list, settings.PAGE_ITEMS_SHOW) # Show 25 contacts per page
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
    # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render_to_response('register/list_all_users.html', {'contacts':contacts,'user_type':user_type}, context_instance=RequestContext(req))

def get_personal_info(req):
    user_id = req.session['user_id']
    user = User.objects.all().filter(keystone_user_id = user_id)[0];
    return render_to_response('register/personal_info.html',{"user":user},context_instance=RequestContext(req))
#从horizon跳转过来
def index(req,param1):
    
    user_id = param1
    userList = User.objects.all().filter(keystone_user_id = user_id);
    if userList.count() > 0:
        user =userList[0]
    else:
        return render_to_response('register/error.html',{"error_message":u"用户未校验,请校验","keystone_user_id":user_id},context_instance=RequestContext(req))
    
    req.session['user_id'] = user_id
    req.session['username'] = user.username
    req.session['usertype'] = user.usertype
    
    if user.usertype != 1:
        keyclient = Keystone()
        v_client = keyclient.admin_login()
        project = keyclient.get_tenant(v_client,user_id)
        user_consumption_list = Consumption.objects.all().filter(project_id = project.id).order_by("-record_time")
        user_charge_list = Charge.objects.all().filter(project_id = project.id).order_by("-txnTime")
        
        consume_money = Decimal(0)
        for temp_consume in user_consumption_list:
            if temp_consume.consume_money >= 0:
                consume_money += temp_consume.consume_money
        tempchargelist=user_charge_list.filter(status = 1)
        charge_money = Decimal(0)
        for temp_charge in tempchargelist:
            if temp_charge.status == 1:
                charge_money += temp_charge.txnAmt
        try:
            latest_charge = tempchargelist[0].txnAmt
        except:
            latest_charge = Decimal(0)
            
        tempcon = user_consumption_list.filter(consume_money__gte=Decimal(0))
        if tempcon.count() > 0:
            latest_consume = tempcon[0].consume_money
        else:
            latest_consume = Decimal(0)
        if user_consumption_list.count() >0 :
            user_money = user_consumption_list[0].remaining_money
        else:
            user_money = Decimal(0)
        return render_to_response('index.html',{'user_money':user_money,'charge_money':charge_money,'consume_money':consume_money,"latest_consume":latest_consume,"latest_charge":latest_charge},context_instance=RequestContext(req))
    else :
        #累计注册人数
        userFilter = User.objects.all()
        total_count = userFilter.count()
        #待审核
        wait_count = userFilter.filter(is_active = 0).count()
        #审核通过
        pass_count = userFilter.filter(is_active = 1).count()
        #审核未通过
        nopass_count = userFilter.filter(is_active = 2).count()
        #充值次数
        charge_count = Charge.objects.all().filter(status = 1).count()
        #新增人数
        now = timezone.now()
        start = now - datetime.timedelta(hours=23, minutes=59, seconds=59)
        today_new = userFilter.filter(createTime__gte = start).count()
        result = {'total_count':total_count,'wait_count':wait_count,'pass_count':pass_count,'nopass_count':nopass_count,'charge_count':charge_count,'today_new':today_new}
        return render_to_response('index.html',result,context_instance=RequestContext(req))
#返回horizon界面
def go_back_to_horizon(req):
    response_data = {}
    response_data['horizon_url'] = settings.LOGIN_URL  
    return HttpResponse(json.dumps(response_data), content_type="application/json")  

def logout(req):
    try:
        del req.session['user_id']
        del req.session['username'] 
        del req.session['usertype'] 
    except KeyError:
        pass
    response_data = {}
    response_data['horizon_url'] = settings.LOGIN_URL  
    return HttpResponse(json.dumps(response_data), content_type="application/json")  

def validate(req):
    userName = req.POST.get('username')
    userPass = req.POST.get('password')
    keystone_user_id = req.POST.get('keystone_user_id')
   
    keyclient = Keystone()
    v_client = keyclient.admin_login()
    flag = False
    flag = keyclient.judgeUserIn(userName,userPass,userName)
    print flag
    if flag:
        #User.objects.filter(username=userName).update(keystone_user_id=keystone_user_id)
        user = keyclient.get_user(v_client,keystone_user_id);
        if keyclient.judgeAttrIsexit(user,'tenantId'):
            registAdd = User.objects.get_or_create(username = userName,password = userPass,email = userName,phone = userName,is_active = 1,keystone_user_id=keystone_user_id,usertype=0)
        else:
            registAdd = User.objects.get_or_create(username = userName,password = userPass,email = userName,phone = userName,is_active = 1,keystone_user_id=keystone_user_id,usertype=1)
        return redirect('/index/'+str(keystone_user_id)+'/')
    else :
        return render_to_response('register/error.html',{"error_message":u"验证失败,重新校验","keystone_user_id":keystone_user_id},context_instance=RequestContext(req))
    
def regist_check(req):
    userName = req.POST.get('username')
    email = req.POST.get('email')
    phone = req.POST.get('phone')
    flag = True
    name_dict = {}
    if User.objects.filter(username=userName).count() > 0 :
        flag = False
        name_dict['value'] = str(userName)+"名字已存在"
    if User.objects.filter(email=email).count() > 0 :
        flag = False
        name_dict['value'] = str(email)+"邮箱已使用"
    if User.objects.filter(phone=phone).count() > 0 :
        flag = False
        name_dict['value'] = str(phone)+"该已使用"   
    name_dict['flag'] = flag
    return HttpResponse(json.dumps(name_dict), content_type='application/json')